<template>
  <div class="async-table">
    <a-button
      type="primary"
      size="small"
      style="margin-right: 8px"
      @click="addRow"
      >添加行</a-button
    >
    <a-button
      type="primary"
      danger
      size="small"
      style="margin-right: 8px"
      @click="delRow"
      :disabled="dataSource.length <= 1"
      >删除行</a-button
    >
    <a-button type="primary" @click="addColumn" size="small">添加列</a-button>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      bordered
      style="margin-top: 12px"
      :pagination="false"
      class="table-edit"
      :scroll="{ x: 860, y: 300 }"
    >
      <!-- 动态表头自定义渲染 -->
      <template #headerCell="{ column }">
        <div class="editable-header">
          <a-input
            v-if="editableHeader === column.dataIndex"
            v-model:value="column.title"
            @pressEnter="saveHeaderEdit(column)"
            @blur="saveHeaderEdit(column)"
          />
          <div class="flex" v-else>
            <div class="title" @click="editHeader(column)">
              {{ column.title }}
            </div>
            <div class="del" @click="handleDel(column)"><DeleteOutlined /></div>
          </div>
        </div>
      </template>
    </a-table>
  </div>
</template>
<script setup>
import { ref, reactive, h, computed } from "vue";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons-vue";
const props = defineProps({
  baseColumns: Array,
  baseData: Array,
});
// 响应式数据
const columns = computed({
  get: () => props.baseColumns,
  set: (val) => {
    props.baseColumns = val;
  },
});
const dataSource = computed({
  get: () => props.baseData,
  set: (val) => {
    props.baseData = val;
  },
});
const editableHeader = ref(null); // 当前编辑的表头key
const editHeader = (column) => {
  editableHeader.value = column.dataIndex;
};
const saveHeaderEdit = (column) => {
  editableHeader.value = null;
};
const handleDel = (column) => {
  const index = columns.value.findIndex(
    (item) => item.dataIndex === column.dataIndex
  );
  columns.splice(index, 1);
};
const addRow = () => {
  dataSource.value.push({});
};
const delRow = () => {
  dataSource.value.pop();
};
const addColumn = () => {
  columns.value.push({ title: "点击编辑", dataIndex: `key${columns.length}` });
};
</script>
<style lang="less" scoped>
.async-table {
  margin-bottom: 20px;
  .table-box {
    width: 100%;
  }
}
.editable-header {
  cursor: pointer;
  .flex {
    display: flex;
    align-items: center;
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      flex: 1;
    }
  }
  .ant-input {
    width: auto;
  }
}
</style>
